<?php 
class Model_Rating extends ZloY_Model_CRUD 
{
	protected $_tableName;
	
	public function __construct($id, $tableName)
	{
		$this->_tableName = $tableName;
		parent::__construct($id);
	}
	
	public static function createItem($id ,$itemName)
	{
		switch ($itemName){
			case 'place' : return new Model_Place($id);
		}
	}
	public function getTable()
	{
		switch($this->_tableName){
			case 'place' : return new Model_DbTable_Rating_Place();
			case 'was'   : return new Model_DbTable_Rating_Was(); 
		}
	}
	
	public function set($item_id, $mark)
	{
		if(Zend_Auth::getInstance()->hasIdentity()){
			if(!$this->isVoted($item_id,  Zend_Auth::getInstance()->getIdentity()->id)){
				$this->_row->item_id = $item_id;
				$this->_row->user_id = Zend_Auth::getInstance()->getIdentity()->id;
				$this->_row->mark = (int) $mark;
				$this->save();
			}
		}
	}
	
	public function isVoted($item_id, $user_id = null)
	{
		if(!Zend_Auth::getInstance()->hasIdentity()){
			return false;
		}
		if($user_id ==null){
			$user_id = Zend_Auth::getInstance()->getIdentity()->id;
		}
		$row = $this->getTable()->fetchRow('item_id = ' . $item_id . ' AND user_id = ' . $user_id);
		if($row){
			return  $row->mark;
		} else {
			return false;
		}
	}
}